import React, { createContext, useState, useEffect } from 'react';
import axios from './axiosInstance';

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [accessToken, setAccessToken] = useState(() => localStorage.getItem('access_token'));

  // 自动刷新token
  useEffect(() => {
    if (!accessToken) return;
    const interval = setInterval(async () => {
      try {
        const { data } = await axios.post('/ltc/refresh-token', {}, { withCredentials: true });
        setAccessToken(data.accessToken);
        localStorage.setItem('access_token', data.accessToken);
      } catch {
        setAccessToken(null);
        localStorage.removeItem('access_token');
      }
    }, 14 * 60 * 1000); // 14分钟刷新一次
    return () => clearInterval(interval);
  }, [accessToken]);

  const login = (token) => {
    setAccessToken(token);
    localStorage.setItem('access_token', token);
  };

  const logout = () => {
    setAccessToken(null);
    localStorage.removeItem('access_token');
  };

  return (
    <AuthContext.Provider value={{ accessToken, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}; 